from aiohttp import web
import queue
import threading
import socket
import urllib.request as urllib
import os
import os.path as path

socket.setdefaulttimeout(30)
routes = web.RouteTableDef()
imageQueue = queue.Queue()
down = True
savePath = "C:/tmp/images3"


@routes.post("/images")
async def post_images(request):
    data = await request.json()
    images = data.get("images")
    print(images)
    for i in images:
        imageQueue.put(i)
    return web.Response(text="Success", status=200)


@routes.get("/switch")
async def switch(request):
    # update global variable
    global down
    if down:
        down = False
    else:
        down = True
        threading.Thread(target=down_image, name="down_image_thread").start()
    print(down)
    return web.Response(text="Success", status=200)


def down_image():
    global down, imageQueue, savePath
    if not path.exists(savePath):
        os.mkdir(savePath)
    while down:
        if not imageQueue.empty():
            print("waiting for download: %s" % imageQueue.qsize())
            img = imageQueue.get()
            name = path.split(img)[1]
            i = name.find("?")
            if i > -1:
                name = name[0:i]
            fullname = path.join(savePath, name)
            if path.exists(fullname):
                continue
            print("begin download photo: %s, %s" % (img, fullname))
            try:
                urllib.urlretrieve(img, fullname)
                print("finish download photo: %s" % name)
            except socket.timeout as e:
                print("error download photo: %s" % name)
                print(e)
            except Exception as e:
                print("error download photo: %s" % name)
                print(e)


def server():
    # 开启下载后台线程，必须在启动服务之前开启
    threading.Thread(target=down_image, name="down_image_thread").start()
    # 启动服务
    app = web.Application()
    app.add_routes(routes)
    web.run_app(app, host="127.0.0.1", port=8088)


if __name__ == "__main__":
    server()
